package com.magic.zhixin.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

public class TokenUtil {
    public static  String getToken() {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                        .getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token) || token.equals("undefined") || token.equals("null")) {
            return null;
        }
        return token;
    }

    public static  Object getUserInfo(){
        Object userAccount = null;
        try {
            String token = getToken();
            userAccount = (Object) ExpireConcurrentMap.newInstance().get(token);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  userAccount;
    }

    /**
     * 生成token
     * @param info
     * @return
     */
    public static String genToken(Object info){
        String token = UUID.randomUUID().toString();
        ExpireConcurrentMap.newInstance().put(token, info, 30 * 60 * 1000l);
        return token;
    }
}
